package com.yuntian.controller.admin;


import com.yuntian.Vo.admin.AdminLoginVo;
import com.yuntian.entity.Admin;
import com.yuntian.properties.JwtProperties;
import com.yuntian.result.Result;
import com.yuntian.service.AdminService;
import com.yuntian.util.JwtUtil;
import org.apache.catalina.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Result<AdminLoginVo> login(@RequestBody Admin admin){

        try {
            // 使用Spring Security进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(admin.getAdminName(), admin.getAdminPass())
            );

            AdminLoginVo adminLoginVo = (AdminLoginVo) authentication.getPrincipal();

            // 生成JWT令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("adminId", adminLoginVo.getAdminId());

            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims
            );

            return Result.success(
                    AdminLoginVo.builder()
                            .adminId(adminLoginVo.getAdminId())
                            .adminName(adminLoginVo.getAdminName())
                            .token(token)
                            .build()
            );

        } catch (Exception e) {
            return Result.error("登录失败，用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.save(admin);
        return Result.success();
    }

    /**
     *
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


}
